from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserModel,Permission,PermissionType,UserGroup
from django.contrib.auth.hashers import make_password,check_password
from utils.myjwt import generate_jwt
import re
# from utils.sms_code import send_message
import json
import calendar
import redis
import random
from mdpro.tasks.sms_code_tasks import send_sms_code
import time
from django.utils.timezone import now
from .serializers import UserSer,UserGroupSer
import re
from django.core.paginator import Paginator
from django.db import transaction
# Create your views here.


# 短信验证码
class SmsCode(APIView):
    def get(self,request):
        # 接受前端数据
        mobile = request.query_params.get('mobile')
        print('接受的前端数据',mobile)

        # 生成随机数字
        data = random.randint(100000, 999999)

        # 异步执行发送验证码
        resp = send_sms_code.delay(mobile,data)  #异步执行，django不会等待
        print("异步队列的响应", resp,dir(resp))
        time.sleep(3)

        # 将随机生成的验证码写到redis
        cae = redis.Redis(host='localhost', port=6379, password='123321')
        cae.set('sms_%s' % mobile, data, ex=60 * 5)

        # 读取异步存储的结果
        cls = redis.Redis(host='localhost', port=6379, password='123321',db=14)

        key = 'celery-task-meta-%s' % str(resp.task_id)
        print('key....',key,type(key))
        print('keydada',cls)
        # 通过redis取出异步结果
        redis_data = cls.get(key)

        print("redis_data>>", redis_data)
        # 把redis中的数据转码
        json_data = redis_data.decode()
        # 把json格式转化为dict
        dict_data = json.loads(json_data)
        # 判断是否发送成功
        if dict_data['status'] == 'FAILURE':
            return Response({'message': "短信验证码发送失败", "code": 500})
        if dict_data['status'] == 'SUCCESS':
            return Response({'message': "短信验证码发送成功", "code": 200})


# 登入
class LoGin(APIView):
    '''登入'''
    def post(self,request):
        # 获取前端信息
        uname = request.data.get('username')
        pwd = request.data.get('password')
        phone = request.data.get('phone')
        sms_code = request.data.get('sms_code')

        print('dasdasf',uname,pwd,phone)

        # 校验手机号正则
        if not phone or not re.search('^1[3-9]\d{9}$',phone):
            return Response({
                'code': 400,
                'message': '手机号不存在或者手机号格式不正确'
            })
        # 判断短信验证码是否正确
        red = redis.Redis(host='localhost', port=6379, password='123321')
        redis_data = red.get('sms_%s' % phone)
        print('验证码', redis_data)
        if not redis_data or redis_data.decode() != sms_code:
            return Response({
                'code': 400,
                'message': '手机验证码不正确'
            })

        # 判断数据库中有没有用户
        try:
            user = UserModel.objects.get(username=uname)



        except Exception as e:
            print('用户不存在',e)
            # 不存在就添加用户,添加用户，密码要用密文存储
            new_paw = make_password(pwd)
            print('密文',new_paw)
            UserModel.objects.create(username=uname,password=new_paw,phone=phone,finally_data=now())

            # 生成token
            data_ = {
                'name':uname
            }


            token = generate_jwt(data_)

            return Response({
                'message':'登入成功',
                'code':201,
                'token':token,
                'user':uname,
            })
        # 存在就登入
        if not check_password(pwd,user.password):
            return Response({
                'code':400,
                'message':'密码错误'
            })
        else:
            # 更新最后登入时间
            user.finally_data = now()
            user.save()
            # 密码正确
            # 生成token
            data_ = {
                'name': user.username,
            }

            token = generate_jwt(data_)
            return Response({
                'code': 200,
                'message': '登入成功',
                'token': token,
                'user': user.username,
            })


# 用户总人数
class UserCountView(APIView):
    def get(self,request):
        # 获取用户总人数
        user_num = UserModel.objects.all().count()

        return Response({
            'total_count':user_num,
            'code':200,
            'msg':'获取成功'
        })

# 日增用户
class UserGrowing(APIView):
    def get(self,request):
        # 当前日期
        present_data = time.strftime('%Y-%m-%d')
        print('dasdasfa',present_data)

        user_num = UserModel.objects.filter(created_data__contains=present_data).count()

        return Response({
            'total_count': user_num,
            'code': 200,
            'msg': '获取成功'
        })

# 日活跃用户
class ActiveView(APIView):
    def get(self,request):
        present_data = time.strftime('%Y-%m-%d')

        user_num = UserModel.objects.filter(finally_data__contains=present_data).count()

        return Response({
            'total_count': user_num,
            'code': 200,
            'msg': '获取成功'
        })


class DangRi(APIView):
    def get(self,request):
        # 当前日期
        year = time.strftime('%Y')
        month = time.strftime('%Y-%m')

        _,days = calendar.monthrange(int(year),int(month[6:]))
        print('这个月有%s天'%days)
        datas = []
        for i in range(1,days+1):
            if i < 10:
                i = '0' + str(i)
            present_data = month + '-' + str(i)
            print('xiaoda',present_data)
            user_num = UserModel.objects.filter(finally_data__contains=present_data).count()
            print('数字',user_num)
            datas.append({
                'count':user_num,
                'date':i,
            })


        return Response({
            'data':datas,
            'code': 200,
            'msg': '获取成功'
        })



class MonthLive(APIView):
    def get(self,request):
        # 当前日期
        year = time.strftime('%Y')
        month = time.strftime('%Y-%m')

        _,days = calendar.monthrange(int(year),int(month[6:]))
        print('这个月有%s天'%days)
        datas = []
        for i in range(1,days+1):
            if i < 10:
                i = '0' + str(i)
            present_data = month + '-' + str(i)
            print('dengd打',present_data)
            user_num = UserModel.objects.filter(finally_data__contains=present_data).count()
            print('dengda打',user_num)
            datas.append({
                'count':user_num,
                'date':i,
            })

        return Response({
            'data':datas,
            'code': 200,
            'msg': '获取成功'
        })

# 获取全部用户
class AlluserView(APIView):
    def get(self, request):
        # 接受前端数据
        page = request.query_params.get('page')
        pagesize = request.query_params.get('pagesize')
        print('前端的分页',page,pagesize)

        user = UserModel.objects.all()
        count = user.count()

        # 分页
        user_page = Paginator(user,pagesize)

        # 每页显示几条
        user_pag = user_page.page(page)

        ser = UserSer(user_pag,many=True)

        return Response({
            'code': 200,
            'results': ser.data,
            'count':count,
            'msg': '返回成功'
        })


# 获取全部用户
class AlluserGetView(APIView):
    def get(self,request):
        user = UserModel.objects.all()
        ser = UserSer(user, many=True)
        return Response(ser.data)
# 添加用户
class AddUserView(APIView):
    def post(self,request):
        # 接受前端数据
        name = request.data.get('username')
        pad = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')

        # 验证
        if not all([name,pad,phone,email]):
            return Response({
                'code':500,
                'msg':'接受前端数据为空',
            })
        # 正则验证  验证用户名
        ers = r'^\w{5,20}'
        if not re.search(ers,name):
            return Response({
                'code':500,
                'msg':'用户名是5到20位数字、字母或下划线'
            })

        # 验证手机号
        ersh = r'^1[34578]\d{9}'

        if not re.search(ersh,phone):
            return Response({
                'code':500,
                'msg':'手机格式不正确',
            })

        # 添加数据
        try:
            UserModel.objects.create(
                username=name,
                password=make_password(pad),
                phone=phone,
                email=email,
                finally_data=now()

            )
            return Response({
                'code':201,
                'msg':'添加成功'
            })
        except Exception as e:
            print('添加时错误',e)
            return Response({
                'code':500,
                'msg':'添加失败',
            })

# 修改用户信息
class AmendView(APIView):
    def get(self, request , id):
        try:
            user = UserModel.objects.filter(id=id)
        except Exception as e:
            print('加载信息失败',e)
            return Response({
                'code':500,
                'msg':'加载信息失败'
            })

        ser = UserSer(user,many=True)

        return Response(ser.data)

    def put(self, request, id):
        # 接受前端数据
        name = request.data.get('username')
        phone = request.data.get('phone')
        email = request.data.get('email')
        paw = request.data.get('password')

        if not all([name,phone,email,paw]):
            return Response({
                'code':500,
                'msg':'没有接受到前端数据'
            })

        # 正则验证
        ers = r'^\w{5,20}'
        if not re.search(ers, name):
            return Response({
                'code': 500,
                'msg': '用户名是5到20位数字、字母或下划线'
            })

        # 验证手机号
        ersh = r'^1[34578]\d{9}'

        if not re.search(ersh, phone):
            return Response({
                'code': 500,
                'msg': '手机格式不正确',
            })

        # 修改数据

        try:
            user = UserModel.objects.get(id=id)
            print('user信息',user)
        except Exception as e:
            print('修改，没有此用户',e)
            return Response({
                'code':500,
                'msg':'没有此用户'
            })

        # 修改
        user.username = name

        if make_password(paw) != user.username:
            user.password = make_password(paw)

        user.email = email
        user.phone = phone
        user.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })
    def delete(self, request ,id):
        try:
            UserModel.objects.get(id=id).delete()
            return Response({
                'code':204,
                'msg':'删除成功'
            })
        except Exception as e:
            print('删除失败',e)
            return Response({
                'code':500,
                'msg':'信息删除失败'
            })

from django.db.models import Q
# 搜索
class SearchView(APIView):
    def get(self, request):
        # 接受数据
        search = request.query_params.get('search')

        user = UserModel.objects.filter(Q(username=search) | Q(phone=search))
        print('哒哒哒',user)

        if not user:
            return Response({
                'code':500,
                'msg':'没有次数据'
            })

        ret = UserSer(user,many=True)

        return Response({
            'code':200,
            'msg':'搜索成功',
            'data':ret.data,
        })



from .serializers import PermissionSer,PermissionTypeSer

# 权限名称
class PermissionView(APIView):
    def get(self,request):
        permission = Permission.objects.all()

        ser = PermissionSer(permission,many=True)

        return Response(ser.data)

    # 添加
    def post(self,request):
        ser = PermissionSer(data=request.data)
        raiser = ser.is_valid(raise_exception=True)

        if raiser:
            # 说明验证成功
            ser.save()

        else:
            # 验证失败
            return Response({
                'code':400,
                'msg':'字段不对，添加失败'
            })
        return Response({
            'code':201,
            'msg':'添加成功'
        })


#
class PermissionZSView(APIView):
    def get(self,request,id):
        print('sadsa',id)
        try:
            per = Permission.objects.get(id=id)
            print('adasfas',per)
        except Exception as e:
            print('没有此信息',e)
            return Response({
                'code':400,
                'msg':'没有此信息'
            })

        ser = PermissionSer(per)
        return Response(ser.data)

    # 修改
    def put(self,request,id):
        print('sadsa', id)
        try:
            per = Permission.objects.get(id=id)
            print('adasfas', per)
        except Exception as e:
            print('没有此信息', e)
            return Response({
                'code': 400,
                'msg': '没有此信息'
            })

        ser = PermissionSer(per,data=request.data)
        raiser = ser.is_valid(raise_exception=True)

        if raiser:
            # 说明验证成功
            ser.save()

        else:
            # 验证失败
            return Response({
                'code': 400,
                'msg': '字段不对，添加失败'
            })
        return Response({
            'code': 200,
            'msg': '修改成功'
        })

    def delete(self,request,id):
        try:
            Permission.objects.get(id=id).delete()
            return Response({
                'code':204,
                'msg':'删除成功'
            })
        except Exception as e:
            print('没有此信息', e)
            return Response({
                'code': 400,
                'msg': '没有此信息'
            })



# 权限类型

class TypesView(APIView):
    def get(self,request):
        type_ = PermissionType.objects.all()

        ser = PermissionTypeSer(type_,many=True)

        return Response(ser.data)


# 用户头像获取

class TouView(APIView):
    def get(self,request):
        # 接受前端数据
        username = request.query_params.get('user')
        try:
            user = UserModel.objects.get(username=username)
        except Exception as e:
            print('大师傅',e)
            return Response({
                'code':400,
                'msg':'没有此用户'
            })

        ser = UserSer(user)
        return Response(ser.data)




# 用户组操作获取添加

class UserGroupGetView(APIView):
    def get(self,request):
        group = UserGroup.objects.all()

        ser = UserGroupSer(group,many=True)

        return Response(ser.data)

    # 添加
    def post(self,request):
        group = UserGroupSer(data=request.data)

        if not group.is_valid(raise_exception=True):
            return Response({
                'code':400,
                'msg':'添加错误'
            })

        group.save()

        return Response({
            'code':201,
            'msg':'添加成功'
        })


# 用户组获取修改删除

class UserGroupPutView(APIView):
    def get(self,request,id):
        try:
            group = UserGroup.objects.get(id=id)
        except Exception as e:
            print('大师傅',e)
            return Response({
                'code':400,
                'msg':'没有此用户组'
            })
        ser = UserGroupSer(group)
        return Response(ser.data)


    def put(self,request,id):
        try:
            group = UserGroup.objects.get(id=id)
        except Exception as e:
            print('大师傅',e)
            return Response({
                'code':400,
                'msg':'没有此用户组'
            })

        ser = UserGroupSer(group,data=request.data)

        if not ser.is_valid(raise_exception=True):
            return Response({
                'code':400,
                'msg':'传入的参数错误'
            })

        ser.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })

# 添加获取管理员
class AdminUser(APIView):
    def get(self,request):
        # 获取所有管理员用户信息
        users = UserModel.objects.filter(is_super_user=True)
        list1 = []
        for i in users:
            list1.append({
                'id':i.id,
                'username':i.username,
                'phone':i.phone,
                'email':i.email
            })
        return Response({
            'code':200,
            'msg':'记载成功',
            'data':list1
        })

    def post(self,request):
        # 接受前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        email = request.data.get('email')

        groups = request.data.get('groups')
        user_permissions = request.data.get('user_permissions')
        print('dasdw前端',username,password,mobile,email,groups,user_permissions)

        if not all([username,password,mobile,email,groups,user_permissions]):
            return Response({
                'code':400,
                'msg':'接受的数据为空'
            })
        print('+++++++++++++1')
        # 不为空就添加
        # 开启一个事物
        with transaction.atomic():
            # 回滚点
            point = transaction.savepoint()

            try:
                user = UserModel.objects.create(
                    username=username,
                    password=make_password(password),
                    phone=mobile,
                    email=email,
                    is_super_user=True,
                )
                # 添加管理员
                print('__________2')
                for i in groups:
                    user_group = UserGroup.objects.filter(id=i)[0]
                    if not user_group:
                        return Response({
                            'code':500,
                            'msg':"没有此用户"
                        })
                    print('______________1')
                    try:
                        user_group.user.add(user)
                        for i in user_permissions:
                            user_group.permission.add(i)
                    except Exception as e:
                        print('用户1权限添加错误',e)
                        transaction.rollback(point)
                        raise ValueError("用户组添加用户和权限错误")
            except Exception as e:
                transaction.rollback(point)
                print('添加错误',e)
                return Response({
                    'code':500,
                    'msg':'添加管理员失败',
                })
            return Response({
                'code':201,
                'msg':'添加成功'
            })

# 获取修改删除管理员
class AdminUserInfoView(APIView):
    def get(self,request,id):
        try:
            user = UserModel.objects.get(id=id,is_super_user=True)
        except Exception as e:
            print('dsadasf',e)
            return Response({
                'code':400,
                'msg':'没有此用户'
            })
        print('________',user)
        ser = UserSer(user)
        return Response(ser.data)

    def put(self,request,id):
        try:
            user = UserModel.objects.get(id=id,is_super_user=True)
        except Exception as e:
            print('dsadasf',e)
            return Response({
                'code':400,
                'msg':'没有此用户'
            })
        '''修改用户名，密码，手机号，邮箱'''
        # 接受前端数据
        username = request.data.get('username')
        password = request.data.get('password')
        mobile = request.data.get('mobile')
        email = request.data.get('email')

        if not all([username,password,mobile,email]):
            return Response({
                'code':400,
                'msg':'接受前端数据为空'
            })

        # 修改用户名
        if user.username != username:
            user.username = username
            user.save()

        # 修改密码
        if user.password != password:
            user.password = make_password(password)
            user.save()

        # 修改手机号
        if user.phone != mobile:
            user.phone = mobile
            user.save()

        # 修改邮箱
        if user.email != email:
            user.email = email
            user.save()

        # 修改用户组和权限
        # 接受前端数据
        groups = request.data.get('groups')
        print('哒哒哒哒',groups)
        user_permissions = request.data.get('user_permissions')

        if groups != user.usergroup_set.all():
            # 说明用户组信息已修改
            try:
                for i in groups:
                    group_user = UserGroup.objects.get(id=i)
                    group_user.user.set([user])
                    group_user.save()
            except Exception as e:
                print('出错信息',e)
                return Response({
                    'code':500,
                    'msg':'修改失败'
                })

            # 我们需要先根据用户找到用户组,然后根据用户组找到所有的权限
            groups = user.usergroup_set.all()
            old_permission = groups[0].permission.all()
            if user_permissions != [i.id for i in old_permission]:
                # 修改权限
                for group in groups:
                    group.permission.set(user_permissions)
                    group.save()

        return Response({
            'code':200,
            'msg':'修改成功'
        })












